import React, { useEffect, useState, useCallback } from 'react';
import Button from 'antd/es/button';
import { useHistory, useLocation } from 'react-router-dom';
import { LeftOutlined, FileOutlined } from '@ant-design/icons';
import {
  Row,
  Col,
  Space,
  Form,
  Input,
  Select,
  Switch,
  message,
  Divider,
  ConfigProvider,
  Table,
  Modal,
} from 'antd';
import './index.scss';
import { useForm } from 'antd/lib/form/Form';
import { Store } from 'antd/lib/form/interface';
import {
  addQa,
  modifyQa,
  getQa,
  getWordModels,
  deleteWordModel,
  getFlowNodes,
} from 'admin/servers/servers';
import { WordModelsInfo, ModifyWordModelRequest } from 'admin/schema/WordModel';
import { ColumnsType } from 'antd/es/table/interface';
import { FlowNodesResponse } from 'admin/schema/QuestionAnswer';
import qs from 'query-string';
import AddWordModel from 'admin/components/AddWordModel';

const layout = {
  labelCol: { span: 4 },
};
const Option = Select.Option;
/**词模--改为扩展问，后来词模问题改动较大，单独分出来OperateQa2；词模逻辑备用 */
export const OperateQa: React.FC = () => {
  // 问答表单
  const [form] = useForm();
  // 当前回答流程的选项
  const [answerFlowType, setAnswerFlowType] = useState<number | null>(null);
  // 路由location
  const location = useLocation();
  const history = useHistory();
  // URL查询字符串=>对象
  const query = qs.parse(location.search);
  // 问答ID
  const [questionId, setQuestionId] = useState<number>(
    query.questionId ? Number(query.questionId) : 0
  );

  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  //  数据总数
  const [total, setTotal] = useState<number>(0);
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // Table数据
  const [wordModels, setWordModels] = useState<WordModelsInfo[]>([]);

  // 删除扩展：弹框显示
  const [deleteVisible, setDeleteVisible] = useState<boolean>(false);
  // 删除扩展：扩展ID
  const [deleteWordModelId, setDeleteWordModelId] = useState<number>(0);
  // 删除扩展：确认按钮loading
  const [confirmDeleteLoading, setConfirmDeleteLoading] = useState<boolean>(false);

  // 新建扩展抽屉弹框 显示/隐藏
  const [addWordModelDrawer, setAddWordModelDrawer] = useState<boolean>(false);
  // 修改扩展弹框数据
  const [modifyWordModelDrawerData, setModifyWordModelDrawerData] = useState<
    ModifyWordModelRequest | undefined
  >();

  // 选择节点列表
  const [flowNodes, setFlowNodes] = useState<FlowNodesResponse[]>([]);

  /**
   * 获取当前回答流程状态
   */
  const getAnswerFlowType = useCallback(() => {
    setAnswerFlowType(form.getFieldValue('answerFlowType'));
  }, [form]);

  /**
   * 对table数据进行重置操作
   */
  const resetWordModelList = async () => {
    if (current !== 1) {
      setCurrent(1);
      return;
    }
    initWordModels();
  };

  /**
   * Table数据加载
   */
  const initWordModels = useCallback(async () => {
    if (!questionId) return;
    setTableLoading(true);
    try {
      const res = await getWordModels({
        pageNo: current,
        pageSize: pageSize,
        intentionId: questionId,
      });
      if (res.code === 0) {
        setWordModels(res.data || []);
        setTotal(Number(res.count) || 0);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('table--->>>>列表查询数据 res', res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [current, pageSize, questionId]);

  /**
   * 点击新建扩展按钮
   */
  const addWordModelAction = () => {
    if (!questionId) {
      // 问题还没有创建
      message.warning('请先输入问答信息并保存');
      return;
    }
    setAddWordModelDrawer(true);
  };

  /**
   * 编辑扩展操作
   * @param index 所编辑数据的index
   */
  const modifyWordModelAction = (index: number) => {
    console.log('编辑扩展', index);
    setModifyWordModelDrawerData(wordModels[index]);
    setAddWordModelDrawer(true);
  };
  /**
   * 删除扩展操作
   *  @param idx 所删除数据的index
   */
  const deleteWordModelAction = (index: number) => {
    console.log('删除扩展', index);
    setDeleteWordModelId(wordModels[index].wordModelId);
    setDeleteVisible(true);
  };

  /**
   * 请求删除扩展接口
   * @param wordModelId
   */
  const requestDeleteWordModel = async (wordModelId: number) => {
    setConfirmDeleteLoading(true);
    try {
      const res = await deleteWordModel({
        wordModelId,
      });
      if (res.code === 0) {
        message.success('删除扩展成功');
        resetWordModelList();
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setDeleteVisible(false);
    setConfirmDeleteLoading(false);
  };

  const columns: ColumnsType<WordModelsInfo> = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
    },
    // {
    //   title: "扩展",
    //   dataIndex: "wordModel",
    //   key: "wordModel",
    // },
    {
      title: '针对问题',
      dataIndex: 'wordModelDescribe',
      key: 'wordModelDescribe',
    },
    {
      title: '扩展类型',
      dataIndex: 'wordModelType',
      key: 'wordModelType',
      render: text => (text === 0 ? '普通扩展' : '排除扩展'),
    },
    {
      title: '操作',
      key: 'operation',
      width: 200,
      render: (text, record, index) => (
        <>
          <Button type="link" onClick={() => modifyWordModelAction(index)}>
            编辑
          </Button>
          <Button type="link" onClick={() => deleteWordModelAction(index)}>
            删除
          </Button>
        </>
      ),
    },
  ];

  /**
   * 提交表单
   */
  const onFinish = async (values: Store) => {
    console.log('onFinish -> values', values);
    const { interruptSwitch, answer, answerFlow, answerFlowType, questionDescribe } = values;
    try {
      // 当前为创建模式 && 第一次创建
      if (query.type === 'add' && !questionId) {
        // 创建问答库
        const res = await addQa({
          versionId: Number(query.versionId),
          interruptSwitch: interruptSwitch ? 'on' : 'off',
          answer: answer.trim(),
          answerFlow,
          answerFlowType,
          questionDescribe: questionDescribe.trim(),
        });
        if (res.code === 0) {
          message.success(`创建成功`);
          setQuestionId(res.data.questionId);
        } else {
          message.error(`${res.tips}(错误码: ${res.code})`);
        }
      } else {
        // 编辑问答库
        const res = await modifyQa({
          questionId: questionId, // 二次保存 || 编辑
          interruptSwitch: interruptSwitch ? 'on' : 'off',
          answer: answer.trim(),
          answerFlow,
          answerFlowType,
          questionDescribe: questionDescribe.trim(),
        });
        if (res.code === 0) {
          message.success(`更新成功`);
        } else {
          message.error(`${res.tips}(错误码: ${res.code})`);
        }
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**
   * 翻页
   * @param pageNo 点击页码
   */
  const onChagneCurrent = (pageNo: number) => {
    setCurrent(pageNo);
  };

  /**
   * 改变每页显示条数
   * @param current 当前页码
   * @param pageSize 每页显示条数
   */
  const onChangePageSize = (current: number, pageSize: number) => {
    setPageSize(pageSize);
  };

  //  分页配置项
  const pagination = {
    total: total,
    showTotal: (total: number) => `共 ${total} 条`,
    current: current,
    pageSize: pageSize,
    showSizeChanger: true,
    onChange: onChagneCurrent,
    onShowSizeChange: onChangePageSize,
  };

  /**
   * 自定义table空状态
   */
  const customizeRenderEmpty = () =>
    !tableLoading && (
      <div style={{ textAlign: 'center' }}>
        <FileOutlined style={{ fontSize: 54, margin: 20 }} />
        <p>新建多条扩展能帮助系统更准确识别出问题！</p>
        <Button type="primary" style={{ margin: 20 }} onClick={addWordModelAction}>
          新建扩展
        </Button>
      </div>
    );

  const getFlowNodeList = useCallback(async () => {
    try {
      const res = await getFlowNodes({ versionId: Number(query.versionId) });
      if (res.code === 0) {
        setFlowNodes(res.data || []);
      }
    } catch (error) {}
  }, [query.versionId]);

  // 1. 进入页面, 判断是创建还是编辑
  // 2. 创建则无处理, 等待用户操作
  // 3. 创建问答完成后, 更新questionId, 方便二次保存
  // 4. 编辑则根据questionId加载当前编辑问答的信息
  // 5. 点击保存更新指定questionId表单信息
  // 6. table: 新建扩展, 判断当前questionId, 有则允许创建, 无则提示先创建问答
  useEffect(() => {
    const initData = async () => {
      try {
        let initForm = {
          answer: '',
          interruptSwitch: false,
          answerFlow: 0,
          answerFlowType: 0,
          questionDescribe: '',
        };
        // 如果是有questionId: 说明是编辑或二次创建保存
        if (questionId) {
          // 查询当前问答信息
          const res = await getQa({
            questionId: questionId,
          });
          if (res.code === 0) {
            const { answer, interruptSwitch, answerFlow, answerFlowType, questionDescribe } =
              res.data;
            initForm = {
              answer,
              interruptSwitch: interruptSwitch === 'on',
              answerFlow,
              answerFlowType,
              questionDescribe,
            };
          }
          initWordModels();
        }
        // 初始化问答form
        form.setFieldsValue(initForm);
        getAnswerFlowType();
      } catch (error) {}
    };
    initData();
    getFlowNodeList();
  }, [form, getAnswerFlowType, getFlowNodeList, initWordModels, questionId]);

  return (
    <>
      <div className="nav">
        <Button
          type="link"
          onClick={() => {
            history.goBack();
          }}
        >
          <LeftOutlined />
          返回
        </Button>
        <div className="title">{query.type === 'add' ? '新建问答' : '编辑问答'}</div>
      </div>
      <div className="operateQa-head">
        <Form form={form} {...layout} onFinish={onFinish}>
          <Row gutter={[0, 10]}>
            <Col span={12}>
              <Form.Item
                label="问题描述"
                name="questionDescribe"
                rules={[{ required: true, max: 50, whitespace: true }]}
              >
                <Input.TextArea
                  placeholder="请输入问题，50个以内字符"
                  maxLength={50}
                ></Input.TextArea>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="答案设置"
                name="answer"
                rules={[{ required: true, max: 350, whitespace: true }]}
              >
                <Input.TextArea
                  placeholder="请输入答案，350个以内字符"
                  maxLength={350}
                ></Input.TextArea>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="是否可以打断" name="interruptSwitch" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="回答流程" name="answerFlowType">
                <Select
                  onChange={getAnswerFlowType}
                  getPopupContainer={triggerNode => triggerNode.parentElement}
                >
                  <Option value={0}>等待用户回应</Option>
                  <Option value={1}>回答后挂机</Option>
                  <Option value={2}>跳回原流程节点</Option>
                  <Option value={3}>指定流程节点</Option>
                </Select>
              </Form.Item>
              {answerFlowType === 3 && (
                <Form.Item
                  name="answerFlow"
                  wrapperCol={{ offset: 4 }}
                  style={{ marginTop: '10px' }}
                >
                  <Select getPopupContainer={triggerNode => triggerNode.parentElement}>
                    {flowNodes.map(item => {
                      return (
                        <Option key={item.id} value={item.id}>
                          {item.title}
                        </Option>
                      );
                    })}
                  </Select>
                </Form.Item>
              )}
            </Col>
          </Row>
          <Row>
            <Col span={12} offset={2}>
              <Space>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
                <Button
                  type="default"
                  onClick={() => {
                    history.goBack();
                  }}
                >
                  取消
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </div>
      <div className="operateQa-content">
        <div>
          <span style={{ fontWeight: 'bold', marginRight: 30 }}>问题扩展</span>
          <Button type="primary" onClick={addWordModelAction}>
            新建扩展
          </Button>
        </div>
        <Divider style={{ margin: '12px 0' }} />
        <ConfigProvider renderEmpty={customizeRenderEmpty}>
          <Table
            columns={columns}
            loading={tableLoading}
            dataSource={wordModels}
            rowKey="wordModelId"
            pagination={pagination}
          />
        </ConfigProvider>
      </div>
      {/* 删除扩展弹框 */}
      <Modal
        title="删除扩展提醒"
        visible={deleteVisible}
        onOk={() => {
          requestDeleteWordModel(deleteWordModelId);
        }}
        confirmLoading={confirmDeleteLoading}
        onCancel={() => {
          setDeleteVisible(false);
        }}
      >
        <p>删除后无法恢复！确定删除吗？</p>
      </Modal>

      {/* 新建、编辑扩展抽屉弹框 */}
      <AddWordModel
        show={addWordModelDrawer}
        intentionId={questionId}
        onClose={() => {
          setAddWordModelDrawer(false);
          setModifyWordModelDrawerData(undefined);
        }}
        onSuccess={() => {
          resetWordModelList();
          setAddWordModelDrawer(false);
          setModifyWordModelDrawerData(undefined);
        }}
        data={modifyWordModelDrawerData}
      />
    </>
  );
};
